import { fromJS } from 'immutable';
import * as actionTypes from './actionTypes';

const defaultState = fromJS({
    users: [],
    chatList: [],
    unRead: 0
})

const setMsg = (chatList, users, userid) => ({
    users: fromJS(users),
    chatList: fromJS(chatList),
    unRead: chatList.filter(item => !item.read && item.to === userid).length
})

export default (state = defaultState, action) => {
    switch(action.type) {
        case actionTypes.MSG_LIST:
            return state.merge(setMsg(action.chatList, action.users, action.userid));
        case actionTypes.MSG_RECV:
            const num =  action.msg.to === action.userid ? 1 : 0;
            return state.merge({
                chatList:fromJS([...state.toJS().chatList, action.msg]),
                unRead: state.toJS().unRead + num
            }); 
        case actionTypes.MSG_READ:
            const { from } = action;
            return state.merge({
                chatList: fromJS(state.toJS().chatList.map(v => {
                    v.read = from === v.from ? true : v.read;
                    return v;
                })),
                unRead: state.toJS().unRead - action.num < 0 ? 0 : state.toJS().unRead - action.num
            })
        default:
            return state;
    }
}